import { _decorator, Texture2D, ImageAsset, resources, SpriteFrame } from "cc";
import { Singleton } from "db://assets/Scripts/Base/Singleton";

export class LoadPictures extends Singleton {
  img2Txture2SpriteFrame(imageAsset: ImageAsset) {
    // 创建 Texture2D 对象
    const texture = new Texture2D();
    texture.image = imageAsset;

    // 创建 SpriteFrame 并设置 Texture2D
    const spriteFrame = new SpriteFrame();
    spriteFrame.texture = texture;
    return spriteFrame;
  }

  loadDirectory(path: string, type: typeof SpriteFrame = SpriteFrame) {
    return new Promise<SpriteFrame[]>((resolve, reject) => {
      resources.loadDir(path, type, function (err, assets) {
        if (err) {
          reject(err);
          return;
        }
        resolve(assets);
      });
    });
  }

  lodeSingleFile(filePath: string, type: typeof SpriteFrame = SpriteFrame) {
    return new Promise<SpriteFrame>((resolve, reject) => {
      resources.load(filePath, type, (err, spriteFrame) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(spriteFrame);
      });
    });
  }

  // 重写getInstance方法,确保返回类型为 CustomEventListener
  static getInstance(): LoadPictures {
    if (!this.instance) {
      this.instance = new this();
    }
    return this.instance as LoadPictures;
  }
}
